/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("tb_project_appendix",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.Entity.DomainModels;
using MYData.System.IServices;
using System.IO;
using System.Web;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.AspNetCore.Authorization;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using MYData.WebApi;

namespace MYData.System.Controllers
{
    public partial class tb_project_appendixController
    {
        private readonly Itb_project_appendixService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public tb_project_appendixController(
            Itb_project_appendixService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 七牛云上传
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadImgToQiNiu")]
        [AllowAnonymous]
        public IActionResult UploadImgToQiNiu(IFormFile files)
        {
            try
            {

                //本地
                //获取文件
                files = HttpContext.Request.Form.Files[0];

                //条件
                //获取文件的后缀名
                var fileExtension = Path.GetExtension(files.FileName);
                //拼接七牛云上传文件格式条件
                var validExtensions = QiNiuConfig.AllowedExtensions.Split(',');
                //定义判断文件格式返回结果
                bool isValidExtension = false;
                //循环遍历上传文件格式是否符合条件
                foreach (var extension in validExtensions)
                {

                    if (fileExtension.Equals(extension.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        isValidExtension = true;
                        break;
                    }
                }
                if (!isValidExtension)
                {
                    throw new Exception("不支持该文件类型");
                }
                //配置上传大小限制
                var fileSizeLimit = QiNiuConfig.MaxSize * 1024 * 1024; // 转换为字节
                if (files.Length > fileSizeLimit)
                {
                    throw new Exception($"文件大小不能超过{QiNiuConfig.MaxSize}MB");
                }

                //生成文件名，可以根据需求修改格式
                string key = files.FileName + "--" + Guid.NewGuid().ToString("N") + fileExtension;

                var path = "wwwroot/Imgs/" + key;
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
                {
                    files.CopyTo(fs);
                }
                //七牛
                Mac mac = new Mac(QiNiuConfig.QiNiuInfo_AccessKey, QiNiuConfig.QiNiuInfo_SecretKey);
                //本地文件路径
                string filePath = path;
                //存储空间名
                string Bucket = "wangmiaodespaceone";
                //设置上传策略，指定上传的文件名
                PutPolicy putPolicy = new PutPolicy();
                putPolicy.Scope = Bucket + ":" + key;
                //上传策略的过期时间(单位:秒)
                putPolicy.SetExpires(3600);
                //文件上传完毕后，在多少天后自动被删除
                putPolicy.DeleteAfterDays = 10;
                //生成上传token
                string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
                Config config = new Config();
                //设置上传区域
                config.Zone = Zone.ZONE_CN_East;
                //设置http或者https上传
                config.UseHttps = true;
                config.UseCdnDomains = true;
                config.ChunkSize = ChunkUnit.U512K;
                //表单上传
                FormUploader target = new FormUploader(config);
                HttpResult result = target.UploadFile(filePath, key, token, null);

                // 构建包含文件名和路径的对象
                var uploadedFileInfo = new UploadedFileInfo
                {
                    FileName = key,
                    FilePath = $"http://rs4k9a2we.hd-bkt.clouddn.com/{key}"
                };
                //返回
                return Ok(uploadedFileInfo);

            }
            catch (Exception ex)
            {
                return Ok(new UploadedFileInfo
                {
                    Code = false,
                    Message = ex.Message,
                });
                throw;
            }
        }
        /// <summary>
        /// 文件上传返回类
        /// </summary>
        public class UploadedFileInfo
        {
            public bool Code { get; set; } = true;
            public string Message { get; set; } = "上传成功";
            public string FileName { get; set; }
            public string FilePath { get; set; }
        }
    }
}
